const db = require('../config/db');

const CartModel = {
  // 获取用户购物车
  getCartByUserId: async (userId) => {
    const [rows] = await db.execute(
      `SELECT c.id, c.product_id, p.name as product_name, p.price, p.image, c.quantity 
       FROM cart c 
       LEFT JOIN products p ON c.product_id = p.id 
       WHERE c.user_id = ?`,
      [userId]
    );
    return rows;
  },
  
  // 添加商品到购物车
  addToCart: async (userId, productId, quantity = 1) => {
    // 检查商品是否已存在
    const [existing] = await db.execute(
      'SELECT * FROM cart WHERE user_id = ? AND product_id = ?',
      [userId, productId]
    );
    
    if (existing.length > 0) {
      // 更新数量
      const [result] = await db.execute(
        'UPDATE cart SET quantity = quantity + ? WHERE user_id = ? AND product_id = ?',
        [quantity, userId, productId]
      );
      return result.affectedRows > 0;
    } else {
      // 新增记录
      const [result] = await db.execute(
        'INSERT INTO cart (user_id, product_id, quantity) VALUES (?, ?, ?)',
        [userId, productId, quantity]
      );
      return result.insertId > 0;
    }
  },
  
  // 更新购物车商品数量
  updateCartItem: async (cartItemId, quantity) => {
    const [result] = await db.execute(
      'UPDATE cart SET quantity = ? WHERE id = ?',
      [quantity, cartItemId]
    );
    return result.affectedRows > 0;
  },
  
  // 从购物车移除商品
  removeFromCart: async (cartItemId) => {
    const [result] = await db.execute('DELETE FROM cart WHERE id = ?', [cartItemId]);
    return result.affectedRows > 0;
  },
  
  // 清空购物车
  clearCart: async (userId) => {
    const [result] = await db.execute('DELETE FROM cart WHERE user_id = ?', [userId]);
    return result.affectedRows > 0;
  }
};

module.exports = CartModel;